# -*- coding: utf-8 -*-
import hashlib
import json

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '6042547795': {
        #  鼎盛支付 支付宝H5 2.3% 100-5000 witch
        'API_KEY': 'wgieriryFj2TvGIrZZ_2LQyGywCzed8VwSszcQby9__WHYTUyta4UGNRTNQ6Q3uCmhwNnipiXM3LQN_LNSaVddb1fMRz_fSgQIKzBfHqe2ghNb',
        'gateway': 'http://hdzw.sodpay.com/PayInterface.aspx',
        'query_gateway': 'http://hdzw.sodpay.com/PayInterface.aspx',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_app_id(mch_id):
    return APP_CONF[mch_id]['appId']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_production_ip(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _gen_sign(s):
    m = hashlib.sha1()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(d, key):
    s = 'pagecode=' + d['pagecode'] + '&mid=' + d['mid'] + '&oid=' + d['oid'] + '&amount=' + d[
        'amount'] + '&ymd=' + d['ymd'] + '&bankno=' + d['bankno'] + key
    return _gen_sign(s)


def generate_notify_sign(d, key):
    s = 'pagecode=' + d['pagecode'] + '&mid=' + d['mid'] + '&oid=' + d['oid'] + '&orderid=' + d[
        'orderid'] + '&result=' + d['result'] + '&value=' + d['value'] + key
    return _gen_sign(s)


def generate_query_sign(d, key):
    s = 'pagecode=' + d['pagecode'] + '&mid=' + d['mid'] + '&tpoid=' + d['tpoid'] + '&type=' + d[
        'type'] + key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("dingshengpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return '1012'
    elif service == 'alipay_pos':
        return '1020'
    return '1012'


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("dingshengpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = [{
        'pagecode': _get_pay_type(service),
        'mid': app_id,
        'oid': str(pay.id),
        'rcvname': str(pay.user_id),
        'rcvaddr': str(pay.user_id),
        'rcvtel': str(pay.user_id),
        'goodsname': 'DSpay',
        'goodsdescription': 'charge',
        'rcvpost': app_id,
        'qq': app_id,
        'amount': '%.2f' % pay_amount,
        'shop_id': app_id,
        'ymd': local_now().strftime('%Y%m%d'),
        'orderstatus': '1',
        'ordername': app_id,
        'bankno': '0000',
        'moneytype': '0',
        'url': '{}/pay/api/{}/dingshengpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id),
        'money': '%.2f' % pay_amount,
        'app': 'app'
    }]
    parameter_dict[0]['sign'] = generate_sign(parameter_dict[0], api_key)
    _LOGGER.info("dingshengpay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict[0]['oid'])
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), json=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("dingshengpay create rsp data: %s %s", response.status_code, response.text)
    data = json.loads(response.text)[0]
    return {'charge_info': data['returnMsg']}


# success
def check_notify_sign(request, app_id):
    _LOGGER.info("dingshengpay notify request.body is: %s", request.body)
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)[0]
    _LOGGER.info("dingshengpay notify data: %s, order_id is: %s", data, data['oid'])
    verify_notify_sign(data, api_key)
    pay_id = data['oid']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('dingshengpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['result'])
    trade_no = str(data['orderid'])
    total_fee = float(data['realvalue'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 成功：2000，失败：2001 等待支付2002。
    if trade_status == '2000':
        _LOGGER.info('dingshengpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = str(pay_order.id)
    api_key = _get_api_key(app_id)
    parameter_dict = [{
        'pagecode': '1008',
        'mid': app_id,
        'tpoid': pay_id,
        'type': '0',
    }]
    parameter_dict[0]['sign'] = generate_query_sign(parameter_dict[0], api_key)
    _LOGGER.info("dingshengpay query data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), json=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("dingshengpay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)[0]
        trade_status = str(data['state'])
        trade_no = pay_order.third_id
        total_fee = float(data['realmoney'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        #  2成功 3失败  4审核中 1处理中 0未支付
        if trade_status == '2':
            _LOGGER.info('dingshengpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('dingshengpay data error, status_code: %s', response.status_code)
